package k8s

import (
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type K8sStatefulset struct {
	Name string						`json:"name"`
	Namespace string				`json:"namespace"`
	Labels map[string]string		`json:"labels"`
	ContainerGroup string			`json:"containergroup"`
	Images []string					`json:"images"`
	RunStatus string				`json:"runStatus"`


	CreateDate string				`json:"createdate"`
	Pods []K8sPod 					`json:"pods"`
	Events []Event					`json:"events"`
}


func GetStatefulsetDetail(ns string,name string)(k8ssts K8sStatefulset,err error) {
	sts, _ := clientset.AppsV1().StatefulSets(ns).Get(name,metav1.GetOptions{})


	k8ssts = K8sStatefulset{
		Name: sts.Name,
		Namespace: sts.Namespace,
		Labels: sts.Labels,
		Images: func() []string{
			var images []string
			for _,i := range sts.Spec.Template.Spec.Containers {
				images = append(images,i.Image)
			}
			return images
		}(),
		CreateDate: sts.CreationTimestamp.Format("2006-01-02 15:04:05"),
		RunStatus: fmt.Sprintf("%d 运行中",sts.Status.ReadyReplicas),
		Events: getEventsForSts(sts),
	}


	Selector , _ := metav1.LabelSelectorAsSelector(sts.Spec.Selector)



	pods,_ := clientset.CoreV1().Pods(ns).List(metav1.ListOptions{
		LabelSelector: Selector.String(),
	})

	for _,pod := range pods.Items {

		var status string
		if pod.Status.ContainerStatuses[0].State.Terminated != nil {
			status = "Terminated " + pod.Status.ContainerStatuses[0].State.Terminated.Reason
		} else if pod.Status.ContainerStatuses[0].State.Running != nil {
			status = "Running"
		} else if pod.Status.ContainerStatuses[0].State.Waiting != nil {
			status = "Waiting " + pod.Status.ContainerStatuses[0].State.Waiting.Reason
		} else {
			status = "Unknown State ! "
		}

		k8ssts.Pods = append(k8ssts.Pods, K8sPod{
			Name:         pod.Name,
			Status:       status,
			//NodeIp:       string(n),
			NodeName: pod.Spec.NodeName,
			PodIp:        pod.Status.PodIP,
			RestartCount: pod.Status.ContainerStatuses[0].RestartCount,
			CreateDate:   pod.CreationTimestamp.Format("2006-01-02 15:04:05"),
		})
	}


	return
}

func getStatefulsets(name string)(k8sStatefulset []K8sStatefulset, err error)  {
	sts,_ := clientset.AppsV1().StatefulSets(name).List(metav1.ListOptions{})

	for _,s := range sts.Items {
		k8sStatefulset = append(k8sStatefulset,K8sStatefulset{
			Name: s.Name,
			Labels: s.Labels,
			ContainerGroup: fmt.Sprintf("%d / %d",s.Status.ReadyReplicas,s.Status.Replicas),
			CreateDate: s.CreationTimestamp.Format("2006-01-02"),
			Images: func() []string{
				var images []string
				for _,i := range s.Spec.Template.Spec.Containers {
					images = append(images,i.Image)
				}
				return images
			}(),
		})
	}

	return
}